﻿#include "RasterAnalysis.h"
#include <QgsRasterLayer.h>
#include <QgsRasterDataProvider.h>
#include <QgsRectangle.h>
#include <QgsRasterBandStats.h>
#include <QDialogButtonBox.h>
#include <QVBoxLayout>
#include <QComboBox.h>
#include <QLabel.h>
#include <QFileDialog.h>
#include <QMessageBox.h>
#include <QTextStream.h>
#include <QFile.h>

RasterAnalysis::RasterAnalysis(QgsMapCanvas* canvas, QObject* parent)
	: QObject(parent), mpMapCanvas(canvas) {
}

// 栅格图层统计
void RasterAnalysis::performRasterLayerStatistics()
{
	QDialog dialog;
	dialog.resize(350, 150);
	dialog.setWindowTitle(tr("选择栅格图层进行统计"));

	QVBoxLayout* layout = new QVBoxLayout(&dialog);

	QLabel* rasterLabel = new QLabel(tr("请选择栅格图层："), &dialog);
	layout->addWidget(rasterLabel);

	// 创建栅格图层下拉框并添加到布局
	QComboBox* rasterComboBox = new QComboBox(&dialog);
	for (QgsMapLayer* l : QgsProject::instance()->mapLayers().values())
	{
		if (l->type() == Qgis::LayerType::Raster)
		{
			rasterComboBox->addItem(l->name(), l->id());
		}
		layout->addWidget(rasterComboBox);

		QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
		layout->addWidget(buttonBox);

		connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
		connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

		if (dialog.exec() == QDialog::Accepted)
		{
			// 获取选中的栅格图层
			QString rasterLayerId = rasterComboBox->currentData().toString();
			QgsRasterLayer* rasterLayer = dynamic_cast<QgsRasterLayer*>(QgsProject::instance()->mapLayer(rasterLayerId));

			if (!rasterLayer)
			{
				QMessageBox::warning(nullptr, tr("错误"), tr("无法找到选择的栅格图层。"));
				return;
			}

			QgsRasterDataProvider* provider = rasterLayer->dataProvider();
			int band = 1; // 波段1
			QgsRectangle extent = rasterLayer->extent(); // 获取栅格图层范围
			// 计算栅格图层的统计信息
			QgsRasterBandStats stats = provider->bandStatistics(band, QgsRasterBandStats::All, extent);

			if (stats.minimumValue == std::numeric_limits<double>::max())
			{
				QMessageBox::warning(nullptr, tr("错误"), tr("无法计算栅格图层的统计信息。"));
				return;
			}

			QString defaultPath = "../Results"; // 设置默认保存路径
			// 弹对话框获取保存路径
			QString fileName = QFileDialog::getSaveFileName(nullptr, tr("保存统计结果"), defaultPath, tr("HTML Files (*.html)"));

			if (fileName.isEmpty())
			{
				return;
			}

			// 打开并写文件
			QFile file(fileName);
			if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
			{
				QMessageBox::warning(nullptr, tr("错误"), tr("无法保存统计结果文件。"));
				return;
			}

			QTextStream out(&file);
			out.setCodec("UTF-8");
			out.setRealNumberNotation(QTextStream::FixedNotation);
			out.setRealNumberPrecision(4);

			// 写入HTML格式的统计结果
			out << tr("<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"UTF-8\">\n<title>栅格图层统计</title>\n</head>\n<body>\n");
			out << tr("<h1>栅格图层统计结果</h1>\n");
			out << tr("<p>分析的文件: ") << rasterLayer->source() << tr(" （波段 ") << band << tr("）</p>\n");
			out << tr("<p>最小值: ") << stats.minimumValue << tr("</p>\n");
			out << tr("<p>最大值: ") << stats.maximumValue << tr("</p>\n");
			out << tr("<p>范围: ") << stats.maximumValue - stats.minimumValue << tr("</p>\n");
			out << tr("<p>总和: ") << stats.sum << tr("</p>\n");
			out << tr("<p>平均值: ") << stats.mean << tr("</p>\n");
			out << tr("<p>标准差: ") << stats.stdDev << tr("</p>\n");
			out << tr("<p>平方和: ") << stats.sumOfSquares << tr("</p>\n");
			out << tr("<p>像元总数: ") << stats.elementCount << tr("</p>\n");
			out << tr("</body>\n</html>");

			file.close();

			QMessageBox::information(nullptr, tr("成功"), tr("统计结果已保存到文件。"));
		}
	}
}
